package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.DeviceListAdapter;
import com.eeepay.eeepay_v2.model.DeviceInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.view.DeviceOperationPopView;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.List;

import cn.eeepay.api.grpc.nano.TerminalApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TerminalSerProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/17 0017.
 * 机具列表
 */
public class DeviceListActivity extends ABBaseActivity implements View.OnClickListener, DeviceOperationPopView.OnCompleteListener {

    private final int DEVICE_ALL = 0;//全部
    private final int DEVICE_CAN_ISSUE = 1;//可下发
    private final int DEVICE_RECYCLE = 2;//机具回收
    private final int DEVICE_ISSUE = 3;//机具下发

    private TitleBar titleBar;
    private TextView head_all, head_canIssue;//全部、 可下发
    private ListView lv_all, lv_canIssue;
    private DeviceListAdapter adapterAll, adapterCanIssue;

    private DeviceOperationPopView popView;

    private boolean isAll = true;
    private String SN, terminalNumber, psam, status, type, merchantNumer, agentNumber,activity_type;//add by zhuangzeqin 2017年8月21日17:37:42  活动类型
    private int pageAll, pageCanIssue;
    private int size = 10;
    private int totalAll, totalCanIssue;//查询到的总数量
    private int lastItemAll, lastItemCanIssue;

    private String issueRecycleSN;
    private String issueAgentNo;
    private String issueAgentNode;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_list;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        head_all = getViewById(R.id.head_1);
        head_canIssue = getViewById(R.id.head_2);

        lv_all = getViewById(R.id.lv_all);
        adapterAll = new DeviceListAdapter(mContext, true);
        lv_all.setAdapter(adapterAll);
        adapterAll.setListener(listener);

        lv_canIssue = getViewById(R.id.lv_can_issue);
        adapterCanIssue = new DeviceListAdapter(mContext, false);
        lv_canIssue.setAdapter(adapterCanIssue);

        if (bundle != null) {
            SN = bundle.getString(Constant.DEVICE_SN);
            terminalNumber = bundle.getString(Constant.TERMINAL_NUMBER);
            psam = bundle.getString(Constant.PSAM_NUMBER);
            status = bundle.getString(Constant.DEVICE_STATUS);
            type = bundle.getString(Constant.DEVICE_TYPE);
            merchantNumer = bundle.getString(Constant.MERCHANT_NAME);
            agentNumber = bundle.getString(Constant.AGENT_NAME);
            activity_type = bundle.getString(Constant.ACTIVITY_TYPE);//add by zhuangzeqin 2017年8月21日17:37:42 活动类型
            initDatas();
        }

    }

    /**
     * 初始化数据
     */
    private void initDatas() {
        pageAll = 1;
        pageCanIssue = 1;
        sendHttpRequest(DEVICE_ALL);
        sendHttpRequest(DEVICE_CAN_ISSUE);
    }


    @Override
    protected void eventOnClick() {
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                String content = ((TextView) view).getText().toString();
                if ("取消".equals(content)) {
                    popView.dismiss();
                } else if ("确定".equals(content)) {
                    if (adapterCanIssue.getBatchIssueSN() == null) {
                        showToast("请选择下发的机具");
                        return;
                    }
                    listener.btnClick(adapterCanIssue.getBatchIssueSN(), Constant.DEVICE_ISSUE
                            , adapterCanIssue.getPositions().size(), false);
                }
            }
        });

        head_all.setOnClickListener(this);
        head_canIssue.setOnClickListener(this);
        //全部
        lv_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("device_detail", adapterAll.getData(position));
                goActivity(DeviceDetailActivity.class, bundle);
            }
        });
        lv_all.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (lastItemAll == adapterAll.getCount()
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    pageAll++;
                    LogUtils.d("TAG", "page = " + pageAll);
                    if ((pageAll - 1) * size < totalAll) {
                        sendHttpRequest(DEVICE_ALL);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastItemAll = firstVisibleItem + visibleItemCount;
            }
        });
        //可下发
        lv_canIssue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("device_detail", adapterCanIssue.getData(position));
                goActivity(DeviceDetailActivity.class, bundle);
            }
        });
        lv_canIssue.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (lastItemCanIssue == adapterCanIssue.getCount()
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    pageCanIssue++;
                    LogUtils.d("TAG", "page = " + pageCanIssue);
                    if ((pageCanIssue - 1) * size < totalCanIssue) {
                        sendHttpRequest(DEVICE_CAN_ISSUE);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastItemCanIssue = firstVisibleItem + visibleItemCount;
            }
        });
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        super.sendHttpRequest(taskId);
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                TerminalApiServiceGrpc.TerminalApiServiceBlockingStub stub = TerminalApiServiceGrpc
                        .newBlockingStub(channel);
//                        .withDeadlineAfter(5, TimeUnit.SECONDS);
                TerminalSerProto.TerminalRequest request;
                switch (taskId) {
                    case DEVICE_ALL:
                    case DEVICE_CAN_ISSUE:
                        request = getRequest(taskId);
                        return stub.getTerminalInfoRpc(request);
                    case DEVICE_RECYCLE://机具回收
                        request = new TerminalSerProto.TerminalRequest();
                        request.loginAgentNo = UserInfo.getUserInfo2SP().getAgentNo();
                        request.loginAgentnode = UserInfo.getUserInfo2SP().getAgentNode();
                        request.sn = issueRecycleSN;
                        return stub.terRecovery(request);
                    case DEVICE_ISSUE://机具下发
                        request = new TerminalSerProto.TerminalRequest();
                        request.issuedSn = issueRecycleSN;
                        LogUtils.d("tag : sn = ", issueRecycleSN);
                        request.issuedAgentNo = issueAgentNo;
                        LogUtils.d("tag : agentNo = ", issueAgentNo);
                        request.issuedAgentNode = issueAgentNode;
                        LogUtils.d("tag : agentNode = ", issueAgentNode);
                        return stub.terIssued(request);
                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null) {
                    showToast("操作失败");
                    return;
                }
                switch (taskId) {
                    case DEVICE_ALL:
                    case DEVICE_CAN_ISSUE:
                        setListDatas(result, taskId);
                        break;
                    case DEVICE_RECYCLE:
                    case DEVICE_ISSUE:
                        TerminalSerProto.ResultTerResponse response = (TerminalSerProto.ResultTerResponse) result;
                        showToast(response.msg);
                        //回收或者下发后都需要刷新数据
                        initDatas();
                        break;
                }
                clearTempData();
            }
        });
    }

    /**
     * 清空暂存的数据
     */
    private void clearTempData() {
        issueRecycleSN = "";
    }

    /**
     * 设置ListView的数据源
     *
     * @param taskId
     * @return
     */
    private void setListDatas(Object result, int taskId) {
        TerminalSerProto.TerminalResponse response = (TerminalSerProto.TerminalResponse) result;
        TerminalSerProto.ResultTerResponse resultMsg = response.resultTerResponse;
        if ("false".equals(resultMsg.status)) {
            showToast(resultMsg.msg);
            return;
        }
        TerminalSerProto.TerminalMsg[] datas = response.terminalMsg;

        List<DeviceInfo> list = new ArrayList<>();
        for (int i = 0; i < datas.length; i++) {
            DeviceInfo info = new DeviceInfo();
            info.setSN(datas[i].sn);
            info.setPasm(datas[i].psam);
            info.setTerminal(datas[i].terId);
            info.setState(datas[i].terStatus);
            info.setModel(datas[i].model);
            info.setStartTime(datas[i].startTime);
            info.setCreateTime(datas[i].createTime);

            info.setAgentName(datas[i].agentName);
            info.setAgentNo(datas[i].agentNo);

            info.setMerchantNo(datas[i].merNo);
            info.setMerchantName(datas[i].merName);

            info.setCanIssue(datas[i].terIssued);
            info.setCanRecycle(datas[i].terRecovery);
            info.setActivityName(datas[i].activityName);//设置活动类型显示的名称
            list.add(info);
        }
        switch (taskId) {
            case DEVICE_ALL:
                totalAll = response.total;
                if(totalAll == 0){
                    showToast("机具数量为0");
                }
                if (pageAll == 1) {
                    adapterAll.setList(list);
                } else {
                    adapterAll.addAll(list);
                }
                break;
            case DEVICE_CAN_ISSUE:
                totalCanIssue = response.total;
                if (pageCanIssue == 1) {
                    adapterCanIssue.setList(list);
                } else {
                    adapterCanIssue.addAll(list);
                }
                break;
        }

    }

    /**
     * 查询机具列表的request
     *
     * @param taskId
     * @return
     */
    private TerminalSerProto.TerminalRequest getRequest(int taskId) {
        TerminalSerProto.TerminalRequest request = new TerminalSerProto.TerminalRequest();
        request.loginAgentNo = UserInfo.getUserInfo2SP().getAgentNo();
        request.loginAgentnode = UserInfo.getUserInfo2SP().getAgentNode();
        LogUtils.d("agentNode = " + UserInfo.getUserInfo2SP().getAgentNode());
        request.sn = SN;
        request.terId = terminalNumber;
        request.pasmNo = psam;
        request.status = (status == null ? "" : status);
        request.postType = ("请选择".equals(type) ? "" : type);
        request.merNameno = merchantNumer;
        request.agentNameno = agentNumber;
        request.pageSize = size;
        request.activityType = activity_type;//add by zhuangzeqin 2017年8月21日18:02:58 新增活动类型的值Value查询
        switch (taskId) {
            case DEVICE_ALL:
                request.pageNo = pageAll;
                request.falg = "1";//是否全部还是显示已下发  1为全部2为可下发
                break;
            case DEVICE_CAN_ISSUE:
                request.pageNo = pageCanIssue;
                request.falg = "2";//是否全部还是显示已下发  1为全部2为可下发
                break;
        }
        return request;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_1: // 全部
                isAll = true;
                head_all.setEnabled(false);
                head_canIssue.setEnabled(true);
                lv_all.setVisibility(View.VISIBLE);
                lv_canIssue.setVisibility(View.GONE);
                titleBar.setShowRight(View.GONE);
                break;
            case R.id.head_2: // 可下发
                isAll = false;
                isAll = true;
                head_canIssue.setEnabled(false);
                head_all.setEnabled(true);
                lv_canIssue.setVisibility(View.VISIBLE);
                lv_all.setVisibility(View.GONE);
                titleBar.setRightTextView("确定");
                titleBar.setShowRight(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (data != null) {
            String agentName = data.getStringExtra("agentName");
            issueAgentNo = data.getStringExtra("agentNo");
            issueAgentNode = data.getStringExtra("agentNode");
            popView.setDatas(agentName);
        }
    }

    public TitleBar getTitleBar() {
        return titleBar;
    }

    /**
     * adapter Item中button点击事件的监听
     */
    private IssueRecycleListener listener = new IssueRecycleListener() {
        @Override
        public void btnClick(String sn, int mode, int count, boolean isAll) {
            LogUtils.d("sn = " + sn);
            issueRecycleSN = sn;
            if (popView == null) {
                popView = new DeviceOperationPopView(mContext, mode);
                popView.setOnCompleteListener(DeviceListActivity.this);
            }
            if (!popView.isShowing()) {
                popView.setMode(mode);
                popView.setIsAll(isAll);
                popView.setCount(count);
                titleBar.setRightTextView("取消");
                titleBar.setShowRight(View.VISIBLE);
                popView.showAsDropDown(titleBar);
            }
        }
    };

    @Override
    public void onComplete(int mode) {
        switch (mode) {
            case Constant.DEVICE_ISSUE://下发
                sendHttpRequest(DEVICE_ISSUE);
                break;
            case Constant.DEVICE_RECYCLE://回收
                sendHttpRequest(DEVICE_RECYCLE);
                break;
        }
    }

    public interface IssueRecycleListener {
        /**
         * 下发和回收机具的回调接口
         *
         * @param sn    操作的机具SN号（可批量）
         * @param mode  操作类型
         * @param count 操作的机具数量
         */
        void btnClick(String sn, int mode, int count, boolean isAll);
    }

}
